package com.example.composewanandroid.ui

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.example.composewanandroid.navigation.MainScreen
import com.example.composewanandroid.navigation.RoutePath
import com.example.composewanandroid.ui.components.WanBottomBar
import com.example.composewanandroid.ui.login.LoginCompose
import com.example.composewanandroid.ui.screens.group.GroupScreen
import com.example.composewanandroid.ui.screens.home.HomeScreen
import com.example.composewanandroid.ui.screens.navigator.NavigatorScreen
import com.example.composewanandroid.ui.screens.profile.ProfileScreen
import com.example.composewanandroid.ui.screens.project.ProjectScreen
import com.example.composewanandroid.ui.search.SearchPage
import com.example.composewanandroid.ui.web.WebViewCompose
import kotlinx.coroutines.launch


@Composable
fun WanApp(navController: NavHostController) {

    NavHost(navController = navController, startDestination = RoutePath.main) {
        composable(route = RoutePath.main) {//主页
            MainScaffold(navController)
        }

        composable(route = RoutePath.login) {//登录页
            LoginCompose(navController)
        }

        composable(//h5
            route = "${RoutePath.web}?url={url}", arguments = listOf(
                navArgument("url") { defaultValue = "https://www.wanandroid.com/" })
        ) {backStackEntry ->
            WebViewCompose(navController,
                backStackEntry.arguments?.getString("url") ?: "https://www.wanandroid.com"
            )
        }

        //文章搜索页
        composable(
            route = RoutePath.ARTICLE_SEARCH + "/{id}",
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ) {
            SearchPage(navController)
        }
    }

}


@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MainScaffold(navHostController: NavHostController) {
    // 创建页面状态（使用Accompanist Pager）
    val pagerState = rememberPagerState(
        pageCount = { MainScreen.values().size } // 页面数量
    )
    // 创建协程作用域
    val scope = rememberCoroutineScope()

    // 当前选中的页面索引（状态）
    var selectedScreen by remember { mutableIntStateOf(0) }

    // 监听页面变化并更新选中状态
    LaunchedEffect(pagerState) {
        Log.d("wenlong", "MainScaffold: 被重新执行了")
        // 使用snapshotFlow将页面状态转换为Flow
        snapshotFlow { pagerState.currentPage }.collect { page ->
            selectedScreen = page
        }
    }

    // 使用Scaffold布局
    Scaffold(
        bottomBar = {
            // 自定义底部导航栏
            WanBottomBar(
                selectedScreen = selectedScreen, // 当前选中项
                onClick = { screenIndex ->
                    // 点击导航项时滚动到对应页面
                    scope.launch {
                        pagerState.scrollToPage(screenIndex)
                    }
                }
            )
        }
    ) { innerPadding ->
        // 水平分页器（实现页面滑动）
        HorizontalPager(
            state = pagerState,
            userScrollEnabled = false, // 禁用用户滑动（仅通过底部导航切换）
            contentPadding = innerPadding // 内边距
        ) { pageIndex ->
            // 根据页面索引显示对应内容
            when (MainScreen.values()[pageIndex]) {
                MainScreen.Home -> HomeScreen(navHostController) // 首页
                MainScreen.Project -> ProjectScreen() // 项目页
                MainScreen.Navigator -> NavigatorScreen() // 导航页
                MainScreen.Group -> GroupScreen() // 分组页
                else -> ProfileScreen() // 个人中心页
            }
        }
    }
}
